package cn.admin.configcenter.registry;


import cn.admin.configcenter.configservice.util.StringUtils;
import cn.admin.configcenter.registry.pojo.PureSubscriberInfo;
import cn.admin.configcenter.registry.pojo.QueryResult;
import cn.admin.configcenter.registry.server.ConfigServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.List;

@RestController
public class ConfigServerApi {

    private static final Logger logger = LoggerFactory.getLogger(ConfigServerApi.class);

    @PostConstruct
    public void init() {
        try {
            ConfigServer.startup();
        } catch (Exception e) {
            logger.error("Registry start Failure",e);
        }
    }

    @RequestMapping(
            method = {RequestMethod.GET},
            value = {"config-center/registry/subscribers", "registry/subscribers"}
    )
    public QueryResult<List<PureSubscriberInfo>> getSubscribers(@RequestParam(defaultValue = "*") String dataIdPattern,
                                                          @RequestParam(defaultValue = "*") String groupIdPattern,
                                                          @RequestParam(defaultValue = "*") String ipPattern) {
        List<PureSubscriberInfo> resultData = null;

        try {
            dataIdPattern = StringUtils.likeSupport(dataIdPattern);
            groupIdPattern = StringUtils.likeSupport(groupIdPattern);
            ipPattern = StringUtils.likeSupport(ipPattern);
            resultData = IOCFactory.getClientManager().getSubscriberInfo(dataIdPattern,
                    groupIdPattern,ipPattern);
        } catch (Exception e) {
            logger.error("Query SubScribers Failure",e);
        }
        return new QueryResult.Builder<List<PureSubscriberInfo>>(200,"getSubScribers").
                setData(resultData).build();
    }

}
